# 导入socket库
from socket import *


def tcp_client():
    # '127.0.0.1'为本地环回地址
    IP = '127.0.0.1'
    # 设置要连接服务端的端口号
    SERVER_PORT = 5000
    # 设置socket缓冲区最多读取512个字节数据
    BUFLEN = 1024

    # 实例化socket对象
    ClientSocket = socket(AF_INET, SOCK_STREAM)

    # socket绑定地址和端口
    ClientSocket.connect((IP, SERVER_PORT))

    while True:
        # 从终端接收数据
        data = input('>>>')
        if data == 'exit':
            break

        # 客户端发送数据，编码为bytes
        ClientSocket.send(data.encode())

        # 等待接收服务端消息
        recv = ClientSocket.recv(BUFLEN)

        # 如果返回空，说明对方关闭了连接，退出循环
        if not recv:
            break

        print(recv.decode())

    # 客户端关闭socket
    ClientSocket.close()


if __name__ == '__main__':
    tcp_client()
